package org.nidy.erp.utils;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Properties;

public class WeaverFileBackupCopier {
    public static void copyFiles() throws IOException {
        Properties properties = new Properties();
        Path configFilePath= Paths.get("src/main/resources/CustomConfig.properties");
        File file = new File(configFilePath.toString());
        if(! file.exists()){
            file.createNewFile();
            properties.setProperty("WeaverSourcePath", "\\\\172.16.70.8\\Nidy");
            properties.setProperty("WeaverTargetPath", "\\\\172.16.100.254\\WeaverBackup\\Nidy");
            properties.setProperty("WeaverSourceUrl", "smb://172.16.70.8/Weaver/Nidy/");
            properties.setProperty("WeaverSourceUser", "administrator");
            properties.setProperty("WeaverSourcePassword", "Gnq@server2024");
            properties.store(new FileOutputStream(file), "");
        }
        properties.load(new FileInputStream(file));
        String url = properties.getProperty("WeaverSourceUrl");
        String user = properties.getProperty("WeaverSourceUser");
        String password = properties.getProperty("WeaverSourcePassword");
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, user, password);
        SmbFile smbFile = new SmbFile(url, auth);
        String weaverSourcePath = properties.getProperty("WeaverSourcePath");
        String weaverTargetPath = properties.getProperty("WeaverTargetPath");
        Path sourceDir = Paths.get(weaverSourcePath);
        Path targetBaseDir = Paths.get(weaverTargetPath);
        Files.createDirectories(targetBaseDir);
        Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Path targetFile = targetBaseDir.resolve(sourceDir.relativize(file));
                Files.copy(file, targetFile, StandardCopyOption.REPLACE_EXISTING);
                return FileVisitResult.CONTINUE;
            }
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                Path targetDir = targetBaseDir.resolve(sourceDir.relativize(dir));
                Files.createDirectories(targetDir);
                return FileVisitResult.CONTINUE;
            }
        });
        System.out.println("文件复制完成！");
    }

}
